package com.zenithmind.exam.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zenithmind.common.result.Result;
import com.zenithmind.exam.pojo.entity.QuestionBank;
import com.zenithmind.exam.service.QuestionBankService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import java.util.List;

/**
 * 题库控制器
 * 
 * @author ZenithMind
 * @since 2024-07-01
 */
@Slf4j
@RestController
@RequestMapping("/api/exam/question-bank")
@RequiredArgsConstructor
@Validated
@Tag(name = "题库管理", description = "题库的增删改查操作")
public class QuestionBankController {

    private final QuestionBankService questionBankService;

    @PostMapping
    @Operation(summary = "创建题库", description = "创建新的题库")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> createQuestionBank(@Valid @RequestBody QuestionBank questionBank) {
        boolean result = questionBankService.createQuestionBank(questionBank);
        return Result.success(result);
    }

    @PutMapping("/{bankId}")
    @Operation(summary = "更新题库", description = "更新指定的题库")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> updateQuestionBank(
            @Parameter(description = "题库ID") @PathVariable @NotBlank String bankId,
            @Valid @RequestBody QuestionBank questionBank) {
        questionBank.setId(bankId);
        boolean result = questionBankService.updateQuestionBank(questionBank);
        return Result.success(result);
    }

    @DeleteMapping("/{bankId}")
    @Operation(summary = "删除题库", description = "删除指定的题库")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> deleteQuestionBank(
            @Parameter(description = "题库ID") @PathVariable @NotBlank String bankId) {
        boolean result = questionBankService.deleteQuestionBank(bankId);
        return Result.success(result);
    }

    @GetMapping("/{bankId}")
    @Operation(summary = "获取题库详情", description = "根据ID获取题库详情")
    public Result<QuestionBank> getQuestionBankById(
            @Parameter(description = "题库ID") @PathVariable @NotBlank String bankId) {
        QuestionBank questionBank = questionBankService.getQuestionBankById(bankId);
        return Result.success(questionBank);
    }

    @GetMapping("/category/{categoryId}")
    @Operation(summary = "根据分类获取题库", description = "根据分类ID获取题库列表")
    public Result<List<QuestionBank>> getQuestionBanksByCategory(
            @Parameter(description = "分类ID") @PathVariable @NotBlank String categoryId) {
        List<QuestionBank> questionBanks = questionBankService.getQuestionBanksByCategory(categoryId);
        return Result.success(questionBanks);
    }

    @GetMapping("/creator/{creatorId}")
    @Operation(summary = "根据创建者获取题库", description = "根据创建者ID获取题库列表")
    public Result<List<QuestionBank>> getQuestionBanksByCreator(
            @Parameter(description = "创建者ID") @PathVariable @NotBlank String creatorId) {
        List<QuestionBank> questionBanks = questionBankService.getQuestionBanksByCreator(creatorId);
        return Result.success(questionBanks);
    }

    @GetMapping("/public")
    @Operation(summary = "获取公开题库", description = "获取所有公开的题库列表")
    public Result<List<QuestionBank>> getPublicQuestionBanks() {
        List<QuestionBank> questionBanks = questionBankService.getPublicQuestionBanks();
        return Result.success(questionBanks);
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询题库", description = "分页查询题库列表")
    public Result<IPage<QuestionBank>> getQuestionBankPage(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "题库标题") @RequestParam(required = false) String title,
            @Parameter(description = "分类ID") @RequestParam(required = false) String categoryId,
            @Parameter(description = "创建者ID") @RequestParam(required = false) String creatorId,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "是否公开") @RequestParam(required = false) Integer isPublic) {
        
        Page<QuestionBank> page = new Page<>(pageNum, pageSize);
        IPage<QuestionBank> result = questionBankService.getQuestionBankPage(page, title, categoryId, creatorId, status, isPublic);
        return Result.success(result);
    }

    @PutMapping("/{bankId}/status")
    @Operation(summary = "更新题库状态", description = "启用或禁用题库")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> updateQuestionBankStatus(
            @Parameter(description = "题库ID") @PathVariable @NotBlank String bankId,
            @Parameter(description = "状态") @RequestParam Integer status) {
        boolean result = questionBankService.updateQuestionBankStatus(bankId, status);
        return Result.success(result);
    }

    @PostMapping("/{bankId}/update-count")
    @Operation(summary = "更新题目数量", description = "更新题库中的题目数量")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> updateQuestionCount(
            @Parameter(description = "题库ID") @PathVariable @NotBlank String bankId) {
        boolean result = questionBankService.updateQuestionCount(bankId);
        return Result.success(result);
    }

    @GetMapping("/tag/{tag}")
    @Operation(summary = "根据标签获取题库", description = "根据标签获取题库列表")
    public Result<List<QuestionBank>> getQuestionBanksByTag(
            @Parameter(description = "标签") @PathVariable @NotBlank String tag) {
        List<QuestionBank> questionBanks = questionBankService.getQuestionBanksByTag(tag);
        return Result.success(questionBanks);
    }

    @GetMapping("/hot")
    @Operation(summary = "获取热门题库", description = "获取热门题库列表")
    public Result<List<QuestionBank>> getHotQuestionBanks(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        List<QuestionBank> questionBanks = questionBankService.getHotQuestionBanks(limit);
        return Result.success(questionBanks);
    }

    @PostMapping("/{bankId}/copy")
    @Operation(summary = "复制题库", description = "复制指定的题库")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> copyQuestionBank(
            @Parameter(description = "题库ID") @PathVariable @NotBlank String bankId,
            @Parameter(description = "新标题") @RequestParam @NotBlank String newTitle) {
        boolean result = questionBankService.copyQuestionBank(bankId, newTitle);
        return Result.success(result);
    }

    @DeleteMapping("/batch")
    @Operation(summary = "批量删除题库", description = "批量删除指定的题库")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> batchDeleteQuestionBanks(
            @Parameter(description = "题库ID列表") @RequestBody List<String> bankIds) {
        boolean result = questionBankService.batchDeleteQuestionBanks(bankIds);
        return Result.success(result);
    }

    @GetMapping("/{bankId}/can-delete")
    @Operation(summary = "检查题库是否可删除", description = "检查指定题库是否可以删除")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> canDeleteQuestionBank(
            @Parameter(description = "题库ID") @PathVariable @NotBlank String bankId) {
        boolean result = questionBankService.canDeleteQuestionBank(bankId);
        return Result.success(result);
    }

    @GetMapping("/creator/{creatorId}/count")
    @Operation(summary = "统计创建者题库数量", description = "统计指定创建者的题库数量")
    public Result<Integer> countByCreator(
            @Parameter(description = "创建者ID") @PathVariable @NotBlank String creatorId) {
        Integer count = questionBankService.countByCreator(creatorId);
        return Result.success(count);
    }
}
